using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.IO.Pipes;

namespace 创建并下载文件.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost(Name ="GetFile")]
        public IActionResult GetFile(IFormFile file)
        {
            string filename = file.FileName;
            //string content = " ";
            //MemoryStream stream = new MemoryStream();
            //file.OpenReadStream().CopyTo(stream);
            //StreamWriter write= new StreamWriter(stream);
            ////write.Write(content);
            //write.Flush();
            //stream.Position = 0; // 将流的位置重置为开始  

            //// 设置HTTP响应的ContentType和文件名  
            Response.Headers.Add("Content-Disposition", $"attachment; filename={filename}");
            Response.ContentType = "text/plain/image/jpeg/jpg/zip";

            // 创建内存流用于写入压缩文件  
            MemoryStream zipStream = new MemoryStream();

            // 创建ZIP压缩存档  
            using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                ZipArchiveEntry entry = archive.CreateEntry(filename);
                using (Stream entryStream = entry.Open())
                {
                    file.CopyTo(entryStream);
                    file.CopyTo(entryStream);
                }
                // 将文件添加到压缩存档
            }

            // 将内存流作为文件流返回  
            return File(zipStream, "text/plain/zip");
        }
    }
}
